package com.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;

@SuppressWarnings("deprecation")
public class DbConnectionManager
{
	private static  XmlBeanFactory bean_factory;
	public static void init() {
		Resource resource = new ClassPathResource("applicationContext-datasource.xml");
		bean_factory = new XmlBeanFactory(resource);

	}
	public static Connection getConnection(String dbName)
	{
		if (null==dbName||"".equals(dbName)||"null".equals(dbName)) {
			dbName = "jdbcTemplate";
		}
		Connection conn = null;
		JdbcTemplate jdbcTemplate = (JdbcTemplate)bean_factory.getBean(dbName);
		try {
			return jdbcTemplate.getDataSource().getConnection();
		} catch (SQLException e) {
			System.out.println("Get DataBase jdbcTemplate error :" + e.getMessage());
		}
		return conn;
	}

	public static void returnConnection(Connection conn) {
		try {
			if ((conn != null) && (!conn.isClosed()))
				conn.close();
		} catch (Exception ex) {
			System.out.println("Close DataBase error:" + ex.getMessage());
		}
	}

	static
	{
		init();
	}
	public static void main(String[] args) {
		DbConnectionManager.getConnection("db_test");
		
	}
}